package cn.itsource.ymcc.producer;

import cn.hutool.db.sql.Order;
import cn.itsource.ymcc.constant.Constants;
import cn.itsource.ymcc.constant.OrderConstants;
import cn.itsource.ymcc.constant.RConst;
import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.domain.CourseOrderItem;
import cn.itsource.ymcc.service.ICourseOrderService;
import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.List;

//保存课程订单以及支付订单的事务消息
@Component
@Slf4j
@RocketMQTransactionListener(
        txProducerGroup = OrderConstants.MQ_COURSEORDER_PAY_GROUP_TRANSACTION
)
public class CourseOrderTransactionListener implements RocketMQLocalTransactionListener {
    @Autowired
    private ICourseOrderService iCourseOrderService;


    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            //获取  订单数据
            if(message == null || message.getPayload() == null || o == null){
                log.error("事务监听器 拿到的数据有问题 {} ,{}",message ,o );
                return RocketMQLocalTransactionState.ROLLBACK;  //事务回滚   不执行事务
            }
            String s = new String((byte[]) message.getPayload(), Constants.UTF8);
            CourseOrder courseOrder = JSON.parseObject(s, CourseOrder.class);
            List<CourseOrderItem>  items = (List<CourseOrderItem>)o;
            //执行本地事务
            iCourseOrderService.save(courseOrder,items);
            return RocketMQLocalTransactionState.COMMIT; //本地事务执行成功
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;  //事务回滚   不执行事务
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        //我不做
        // 这里面是做检查的
        // 直接获取 订单编号去查询数据  看有么有保存成功

        // 如果有数据 就返回 commit
        // 如果没有数据  就返回 rollback
        return RocketMQLocalTransactionState.COMMIT;
    }
}
